package cn.hd01.weixin;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hd01.repository.entity.Banner;
import cn.hd01.repository.entity.Product;
import cn.hd01.repository.entity.Upload;
import cn.hd01.repository.entity.User;
import cn.hd01.repository.entity.ViewHistory;
import cn.hd01.repository.entity.WXOauth;
import cn.hd01.service.BannerService;
import cn.hd01.service.DictionaryService;
import cn.hd01.service.ProductService;
import cn.hd01.service.UploadService;
import cn.hd01.service.UserService;
import cn.hd01.service.ViewHistoryService;
import cn.hd01.util.DictionaryType;
import cn.hd01.web.auth.Auth;
import cn.hd01.web.auth.AuthType;
import cn.hd01.web.util.WebHelper;

import java.util.List;

@Controller
@RequestMapping("/weixin/product")
@Auth(AuthType.WECHAT)
public class WXProductController {
	@Autowired
	private ProductService productService;

	@Autowired
	private DictionaryService dictionaryService;
	
	@Autowired
	private BannerService bannerService;

	@Autowired
	private UploadService uploadService;
	
	@Autowired
	private ViewHistoryService vhService;

	@Autowired
	private UserService userService;
	
	@RequestMapping(path = { "/", "" }, method = RequestMethod.GET)
	public String index(Model model) {
		model.addAttribute("types", dictionaryService.findByType(DictionaryType.PRODUCT_TYPE));
		model.addAttribute("banners", bannerService.findByType(Banner.TYPE_PRODUCT));
		return "weixin/product";
	}

	@ResponseBody
	@RequestMapping(path = { "/list" }, method = RequestMethod.GET)
	public Page<Product> List(String hot, String type, @PageableDefault Pageable pageable) {
		Product product = new Product();

		if ("0".equals(hot)) {
			product.setHot(true);
		}

		if ("1".equals(hot)) {
			product.setRecommend(true);
		}

		if (StringUtils.hasText(type)) {
			product.setType(Integer.valueOf(type));
		}
		return productService.findAll(product, pageable);
	}

	@RequestMapping(path = { "/detail/{id}" }, method = RequestMethod.GET)
	public String detail(Model model, @PathVariable Integer id) {
		WXOauth oauth = WebHelper.currentWXOauth();
		User user = userService.findByOauthId(oauth.getId());
		vhService.view(user.getId(), ViewHistory.TYPE_PRODUCT, id);
		
		List<Upload> imgs = uploadService.findByTypeAndRefIdOrderBySortAsc("product", id);
		model.addAttribute("imgs", imgs);
		model.addAttribute("product", productService.findOne(id));
		return "weixin/productDetail";
	}
}
